package logic

import (
	"cartRpc/models"
	"cartRpc/pkg"
	"context"
	"errors"

	"cartRpc/cart"
	"cartRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *cart.LoginRequest) (*cart.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var u models.User
	u.Models = in.Models

	if err = u.GetUserByAccount(); err != nil {
		logx.Error("用户信息获取失败")
		return nil, errors.New("用户信息获取失败")
	}
	if u.ID == 0 {
		u.Password = pkg.Md5(in.Password)
		if err = u.Register(); err != nil {
			logx.Error("用户注册失败")
			return nil, errors.New("用户注册失败")
		}
	}

	if u.Password != pkg.Md5(in.Password) {
		logx.Error("密码错误")
		return nil, errors.New("密码错误")
	}

	return &cart.LoginResponse{
		Id: int64(u.ID),
	}, nil
}
